#!/usr/bin/env node

/**
 * Docker PostgreSQL 连接调试脚本
 */

const { Pool } = require('pg')

async function testConnection(config, description) {
  console.log(`\n🔧 测试连接: ${description}`)
  console.log(`   用户: ${config.user}`)
  console.log(`   密码: ${config.password ? config.password : '未设置'}`)
  console.log(`   主机: ${config.host}:${config.port}`)
  console.log(`   数据库: ${config.database}`)
  
  const pool = new Pool(config)
  
  try {
    const client = await pool.connect()
    console.log('✅ 连接成功!')
    
    // 测试查询
    const result = await client.query('SELECT version()')
    console.log('📋 PostgreSQL版本:', result.rows[0].version.split(' ')[0] + ' ' + result.rows[0].version.split(' ')[1])
    
    // 检查现有数据库
    const dbResult = await client.query('SELECT datname FROM pg_database WHERE datistemplate = false ORDER BY datname')
    console.log('📊 现有数据库:')
    dbResult.rows.forEach(row => {
      console.log(`   - ${row.datname}`)
    })
    
    client.release()
    return true
  } catch (error) {
    console.log('❌ 连接失败:', error.message)
    console.log('   错误代码:', error.code)
    return false
  } finally {
    await pool.end()
  }
}

async function debugDockerConnection() {
  console.log('🐳 Docker PostgreSQL 连接调试')
  console.log('=' .repeat(50))
  
  // 测试1: 使用Docker设置的原始密码
  await testConnection({
    host: 'localhost',
    port: 5432,
    database: 'postgres', // 默认数据库
    user: 'postgres',
    password: 'unidt@123' // Docker中设置的原始密码
  }, 'Docker原始密码')
  
  // 测试2: 无密码
  await testConnection({
    host: 'localhost',
    port: 5432,
    database: 'postgres',
    user: 'postgres',
    password: ''
  }, '无密码')
  
  // 测试3: URL解码后的密码
  await testConnection({
    host: 'localhost',
    port: 5432,
    database: 'postgres',
    user: 'postgres',
    password: decodeURIComponent('unidt%40123')
  }, 'URL解码密码')
  
  console.log('\n🔍 环境变量检查:')
  console.log('   DATABASE_URL:', process.env.DATABASE_URL || '未设置')
  console.log('   POSTGRES_PASSWORD:', process.env.POSTGRES_PASSWORD || '未设置')
}

if (require.main === module) {
  debugDockerConnection()
}
